package com.shure.modules.docs.controller;

import com.itextpdf.text.pdf.BaseFont;
import com.shure.utils.HtmlTagCloser;
import com.youbenzi.md2.export.FileFactory;
import jakarta.servlet.http.HttpServletResponse;
import org.docx4j.Docx4J;
import org.docx4j.convert.in.xhtml.XHTMLImporterImpl;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@RestController
@RequestMapping("/export")
public class ExportController {

    @PostMapping("/word")
    public void toWord(HttpServletResponse response, @RequestBody Map content) throws Exception {
        String html = content.get("html").toString();
        html = HtmlTagCloser.forceCloseTags(html);
        exportWord(response, html);
    }

    @PostMapping("/pdf")
    public void toPdf(HttpServletResponse response, @RequestBody Map content) throws Exception {
        String html = content.get("html").toString();
        html = HtmlTagCloser.forceCloseTags(html);
        exportPdf(response, html);
    }

    /**
     * @param content 富文本内容
     */
    private void exportWord(HttpServletResponse response, String content) throws Exception {

        // 预处理HTML内容
        String xhtml = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"/></head><body>"
                + content.replace("&", "&amp;")
                + "</body></html>";

        // 创建Word文档
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

        // 创建XHTML导入器
        XHTMLImporterImpl xhtmlImporter = new XHTMLImporterImpl(wordMLPackage);

        // 转换HTML到Word
        wordMLPackage.getMainDocumentPart().getContent().addAll(
                xhtmlImporter.convert(xhtml, null)
        );

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment;filename=export.docx");

        // 输出文档
        Docx4J.save(wordMLPackage, response.getOutputStream());
        response.getOutputStream().flush();
    }

    private void exportPdf(HttpServletResponse response, String content) throws Exception {
        // 包装成XHTML
        String xhtml = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"/>" +
                "<style>body { font-family: SimSun; }</style></head><body>" +
                content.replace("&", "&amp;") +
                "</body></html>";

        // 设置响应头
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=export.pdf");

        // 创建PDF渲染器
        ITextRenderer renderer = new ITextRenderer();

        // 从classpath加载字体
        InputStream fontStream = getClass().getResourceAsStream("/fonts/SimSun.ttf");
        if (fontStream != null) {
            renderer.getFontResolver().addFont(
                    "/fonts/SimSun.ttf",
                    BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED
            );
            fontStream.close();
        }

        renderer.setDocumentFromString(xhtml);
        renderer.layout();
        renderer.createPDF(response.getOutputStream());
    }


    @PostMapping("/md")
    public void mdToDoc(HttpServletResponse response, @RequestBody Map content) throws Exception {
        String mdStr = content.get("md").toString();
        String type = content.get("type").toString();
        String filePath = "./temp/export.";
        if ("pdf".equals(type)) {
            filePath += "pdf";
            FileFactory.produce(mdStr, filePath);
        }
        if ("word".equals(type)) {
            filePath += "docx";
            FileFactory.produce(mdStr, filePath);
        }
        download(response, filePath);
    }

    private void download(HttpServletResponse response, String filePath) throws Exception {
        // 这里实现文件下载逻辑
        File file = new File(filePath);
        if (!file.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            return;
        }

        // 根据文件扩展名设置Content-Type
        String contentType;
        if (filePath.endsWith(".pdf")) {
            contentType = "application/pdf";
        } else if (filePath.endsWith(".docx")) {
            contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        } else {
            contentType = "application/octet-stream";
        }

        response.setContentType(contentType);
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        response.setContentLength((int) file.length());

        try (InputStream in = new FileInputStream(file);
             OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } finally {
            // 删除临时文件
            file.delete();
        }
    }
}

